import axios from "axios";
import router from "@/router";

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    timeout: 3000000 // 请求时间 300秒
})

// 请求拦截
service.interceptors.request.use(request => {
    request.headers['Authorization'] = sessionStorage.getItem('jwt')
    return request
}, error => {
    return Promise.reject(error)
})

// 响应拦截
service.interceptors.response.use(response => {
    if (response.headers['access-token']){
        sessionStorage.setItem('jwt', response.headers['access-token'])
        sessionStorage.setItem('userInfo',response.headers['userInfo'])
    }

    var data = response.data.code;
    switch (data){
        case 40003:
            console.log('没有权限')
            router.push({path: '/403'})
            break
        case 40004:
            sessionStorage.setItem('jwt','')
            sessionStorage.setItem('userInfo', {})
            router.push({ path: '/' })
            break
    }

    return response
}, error => {
    return Promise.reject(error)
})

export default service
